//
//  oldRippleView.m
//  laonianbang
//
//  Created by 勇拓 李 on 17/10/19.
//  Copyright © 2017年 zaiyou. All rights reserved.
//

#import "oldRippleView.h"
#import <AVFoundation/AVFoundation.h>
#import "oldHub.h"
#import "oldVoiceManager.h"

@interface oldRippleView()<AVAudioRecorderDelegate>
@property (nonatomic, strong) UIButton *rippleButton;
//@property (nonatomic, strong) UIView *centerView;
@property (nonatomic, strong) NSTimer *rippleTimer;
@property (nonatomic, assign) NSInteger mode;
@property (nonatomic, assign) BOOL isTurnOn;

@property (nonatomic,strong) AVAudioRecorder *audioRecorder;//音频录音机
@property (nonatomic, assign)float recordtime;//记录录音时长
@end

#define Radius 240
#define LIMIT_TIME 30.f

@implementation oldRippleView

- (void)removeFromParentView
{
    if (self.superview) {
        [_rippleButton removeFromSuperview];
        [self closeRippleTimer];
        [self removeAllSubLayers];
        [self removeFromSuperview];
        [self.layer removeAllAnimations];
    }
}

- (void)removeAllSubLayers
{
    for (NSInteger i = 0; [self.layer sublayers].count > 0; i++) {
        [[[self.layer sublayers] firstObject] removeFromSuperlayer];
    }
}

- (void)removeAllCAShapeLayer
{
    NSMutableArray *array = [NSMutableArray array];
    NSArray *layArray = [self.layer sublayers];
    
    for (NSInteger i = 0; i < [layArray count]; i++) {
        if([[self.layer sublayers][i] isKindOfClass:[CAShapeLayer class]])
        {
            [array addObject:[self.layer sublayers][i]];
        }
    }
    
    for (int i = 0; i < [array count]; i++) {
        [array[i] removeFromSuperlayer];
    }
}

- (void)showWithRipple
{
    [self setUpRippleButton];
}

- (void)startTimer
{
    self.rippleTimer = [NSTimer timerWithTimeInterval:.5 target:self selector:@selector(addRippleLayer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:_rippleTimer forMode:NSRunLoopCommonModes];
}

- (void)setUpRippleButton
{
    _rippleButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, Radius, Radius)];
    _rippleButton.center = self.center;
//    _rippleButton.layer.backgroundColor = OLD_YELLOW.CGColor;
    _rippleButton.layer.cornerRadius = Radius/2;
    _rippleButton.layer.masksToBounds = YES;
//    _rippleButton.layer.borderColor = [UIColor yellowColor].CGColor;
//    _rippleButton.layer.borderWidth = 2;
    [_rippleButton setImage:[UIImage imageNamed:@"语音图标"] forState:UIControlStateNormal];
    [_rippleButton setImage:[UIImage imageNamed:@"语音图标"] forState:UIControlStateHighlighted];
    [_rippleButton addTarget:self action:@selector(rippleButtonTouched:) forControlEvents:UIControlEventTouchDown];
    
    [_rippleButton addTarget:self action:@selector(stoptouch:) forControlEvents:UIControlEventTouchUpInside];
    
    [self addSubview:_rippleButton];
}

- (void)rippleButtonTouched:(id)sender
{
    _isTurnOn = !_isTurnOn;
    
    [self recordClick];
    [self startTimer];
    [self.delegate oldRipperViewBtnClick:YES error:NO];
}

- (void)stoptouch:(id)sender
{
    _isTurnOn = !_isTurnOn;
    
    [self closeRippleTimer];
    [self removeAllCAShapeLayer];
    [self.delegate oldRipperViewBtnClick:NO error:[self stopRecord:sender]];
}

- (CGRect)makeEndRect
{
    CGRect endRect = CGRectMake(_rippleButton.frame.origin.x, _rippleButton.frame.origin.y, Radius, Radius);
    endRect = CGRectInset(endRect, -80, -80);
    return endRect;
}

- (void)addRippleLayer
{
    CAShapeLayer *rippleLayer = [[CAShapeLayer alloc] init];
    rippleLayer.position = CGPointMake(200, 200);
    rippleLayer.bounds = CGRectMake(0, 0, 400, 400);
    rippleLayer.backgroundColor = [UIColor clearColor].CGColor;
    
    UIBezierPath *path = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_rippleButton.frame.origin.x, _rippleButton.frame.origin.y, Radius, Radius)];
    rippleLayer.path = path.CGPath;
    rippleLayer.strokeColor = Color_With_Rgb(255,218,12,0.3).CGColor;
    
    rippleLayer.fillColor = Color_With_Rgb(255,218,12,0.3).CGColor;
    
    [self.layer insertSublayer:rippleLayer below:_rippleButton.layer];
    
    //addRippleAnimation
    UIBezierPath *beginPath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(_rippleButton.frame.origin.x, _rippleButton.frame.origin.y, Radius, Radius)];
    CGRect endRect = CGRectInset([self makeEndRect], -50, -50);
    UIBezierPath *endPath = [UIBezierPath bezierPathWithOvalInRect:endRect];
    
    rippleLayer.path = endPath.CGPath;
    rippleLayer.opacity = 0.0;
    
    CABasicAnimation *rippleAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    rippleAnimation.fromValue = (__bridge id _Nullable)(beginPath.CGPath);
    rippleAnimation.toValue = (__bridge id _Nullable)(endPath.CGPath);
    rippleAnimation.duration = 1.5;
    
    CABasicAnimation *opacityAnimation = [CABasicAnimation animationWithKeyPath:@"opacity"];
    opacityAnimation.fromValue = [NSNumber numberWithFloat:0.6];
    opacityAnimation.toValue = [NSNumber numberWithFloat:0.0];
    opacityAnimation.duration = 1.5;
    
    [rippleLayer addAnimation:opacityAnimation forKey:@""];
    [rippleLayer addAnimation:rippleAnimation forKey:@""];
    
    [self performSelector:@selector(removeRippleLayer:) withObject:rippleLayer afterDelay:1.5];
    
    _recordtime -= 0.5;
    if (_recordtime == 0) {
        [self stoptouch:nil];
    }
}

- (void)removeRippleLayer:(CAShapeLayer *)rippleLayer
{
    [rippleLayer removeFromSuperlayer];
    rippleLayer = nil;
}

- (void)closeRippleTimer
{
    if (_rippleTimer) {
        if ([_rippleTimer isValid]) {
            [_rippleTimer invalidate];
        }
        _rippleTimer = nil;
    }
}

#pragma mark record
/**
 *  获得录音机对象
 *
 *  @return 录音机对象
 */
-(AVAudioRecorder *)audioRecorder{
    if (!_audioRecorder) {
        //创建录音文件保存路径
        NSURL *url =  [NSURL URLWithString:[oldVoice getSavePath]];
        //创建录音格式设置
        NSDictionary *setting = [self getAudioSetting];
        //创建录音机
        NSError *error=nil;
        _audioRecorder=[[AVAudioRecorder alloc]initWithURL:url settings:setting error:&error];
        _audioRecorder.delegate = self;
        _audioRecorder.meteringEnabled=YES;//如果要监控声波则必须设置为YES
        if (error) {
            NSLog(@"创建录音机对象时发生错误，错误信息：%@",error.localizedDescription);
            return nil;
        }
    }
    return _audioRecorder;
}

/**
 *  取得录音文件设置
 *
 *  @return 录音设置
 */
-(NSDictionary *)getAudioSetting{
    NSMutableDictionary *dicM = [NSMutableDictionary dictionary];
    //设置录音格式
    //    [dicM setObject:@(kAudioFormatLinearPCM) forKey:AVFormatIDKey];
    //    [dicM setObject:@(kAudioFormatMPEG4AAC) forKey:AVFormatIDKey];
    //    //每个采样点位数,分为8、16、24、32
    //    [dicM setObject:@(YES) forKey:AVLinearPCMIsFloatKey];
    //....其他设置等
    
    [dicM setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];//
    
    //设置录音采样率，8000是电话采样率，对于一般录音已经够了
    [dicM setObject:@(8000) forKey:AVSampleRateKey];
    //设置通道,这里采用单声道
    [dicM setObject:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];
    
    [dicM setObject:@(16) forKey:AVLinearPCMBitDepthKey];
    //是否使用浮点数采样
    [dicM setValue:[NSNumber numberWithInt:AVAudioQualityMin] forKey:AVEncoderAudioQualityKey];//音频质量
    
    return dicM;
}

- (void)recordClick{
    
    //    if (SIMULATOR) {
    //        [Utils warningUser:self msg:@"请使用真机测试录音！"];
    //        return;
    //    }
    
    WeakSelf
    
    [[AVAudioSession sharedInstance] requestRecordPermission:^(BOOL granted) {
        if (granted) {
            [weakSelf audioRecorder];
            
            if(!_audioRecorder)
            {
                return;
            }
            
            [weakSelf DelayRecord];
            
        } else {
            [oldHub warningUser:@"请开启麦克风权限！"];
        }
    }];
}

- (void)DelayRecord
{
    if (_isTurnOn == NO) {
        return;
    }
    
    
    if (![self.audioRecorder isRecording]) {
        
        [self setAudioSession];
        [self.audioRecorder record];//首次使用应用时如果调用record方法会询问用户是否允许使用麦克风
    }
    
    [self initRecordTimer];
}

/**
 *  设置音频会话
 */
-(void)setAudioSession{
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //设置为播放和录音状态，以便可以在录制完之后播放录音
    [audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
    
    [audioSession setActive:YES error:nil];
}

- (void)initRecordTimer
{
    _recordtime = LIMIT_TIME;
}

- (BOOL)stopRecord:(id)sender
{
    if (!_audioRecorder) {
        return YES;
    }
    
    _recordtime = _audioRecorder.currentTime;
    
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    NSError *err = nil;
    [audioSession setCategory :AVAudioSessionCategoryPlayback error:&err];
    
    [self.audioRecorder stop];
    
    if(_recordtime > 3)
    {
        [self saveVoice];
        if (sender == nil) {
            [oldHub warningUser:@"语音不能超过30秒"];
        }
        
        return NO;
    }
    else
    {
        [oldHub warningUser:@"录音时间太短"];
        return YES;
    }
}

- (void)saveVoice
{
    
}

#pragma mark - 录音机代理方法
/**
 *  录音完成，录音完成后播放录音
 *
 *  @param recorder 录音机对象
 *  @param flag     是否成功
 */
-(void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag{
    NSLog(@"录音完成!");
    if (_recordtime > 1) {
        
    }
    else
    {
        [recorder deleteRecording];
    }
}


@end
